//
//  RatingVC.m
//  ImGuider
//
//  Created by llt on 2017/6/22.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "RatingVC.h"
#import "StarRateView.h"
#import <IQTextView.h>
#import "LineQuestionHeadView.h"
#import <IQKeyboardManager.h>
@interface RatingVC () <StarRateViewDelegate,UITextViewDelegate,UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet StarRateView *rateView;

@property (nonatomic) CGFloat score;
//@property (nonatomic, strong) NSArray *messageArray;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *lineView;

@property (weak, nonatomic) IBOutlet IQTextView *commentTextView;
@property (weak, nonatomic) IBOutlet UILabel *CharLimitLabel;

@property (weak, nonatomic) IBOutlet LineQuestionHeadView *LineQuestionHeadView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *toTopSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *titleLabelToTopSapce;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *textH;

@property (nonatomic, strong) UIButton * commitBtn;
@property (nonatomic, copy) void (^ commitBlock) (CGFloat score, NSString *comment);

@property (weak, nonatomic) IBOutlet UIButton *submitCommentBtn;

@property (weak, nonatomic) IBOutlet UIButton *feedBackBtn;

@property (weak, nonatomic) IBOutlet UIView *bgView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bgViewCenterY;


@end

@implementation RatingVC

- (void)viewDidLoad {
    
    [super viewDidLoad];
//    [IQKeyboardManager sharedManager].enable = NO;
     [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
//    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    
    self.commentTextView.layer.borderWidth = 1.0;
    self.commentTextView.layer.borderColor = kBGColor.CGColor;
    self.bgViewCenterY.constant = kScreenHeight/2;
    
    if (ISiPhone5 || ISiPhone4) {
        
        self.textH.constant = 120;
    }
    self.submitCommentBtn.layer.cornerRadius = 5;
    self.submitCommentBtn.clipsToBounds = YES;
    self.bgView.layer.cornerRadius = 5;
    self.bgView.clipsToBounds = YES;
    self.view.backgroundColor = [UIColor colorWithWhite:0 alpha:0.57];
    [self setup];
    
//     [self.navigationController setNavigationBarHidden:YES animated:NO];
    
}

- (void)setup {
    
    self.titleLabelToTopSapce.constant = kNavigationBarHeight + 20;
    self.toTopSpace.constant = kNavigationBarHeight;
    self.titleLabel.textColor = kTitleColor;
    self.CharLimitLabel.textColor = kContentColor;
    self.commentTextView.textColor = kContentColor;
    self.rateView.delegate = self;
    self.rateView.canRating = YES;
    [self.rateView setScore:4];
    
    self.titleLabel.text = MYLocalizedString(@"PUBLIC_COMMENT_CONTENT", nil);
    
    // [self.commentedBtn setTitle:MYLocalizedString(@"PUBLIC_OK", nil) forState:UIControlStateNormal];
    
    //self.commentedBtn.hidden = YES;
    
    //    if (self.isLineQuestion) {
    //        self.title = MYLocalizedString(@"SITEPLAY_SUBMIT_QUESTION", nil);;
    //
    //        self.LineQuestionHeadView.lineName = self.lineModel.linename;
    //        self.LineQuestionHeadView.headerImageName = self.lineModel.guide.headimg;
    //        self.LineQuestionHeadView.vip = self.lineModel.guide.vip;
    //
    //        self.LineQuestionHeadView.guiderName = self.lineModel.guide.realname;
    //        self.commentTextView.placeholder =MYLocalizedString(@"SITEPLAY_QUESTION_TIPS", nil);// SITEPLAY_QUESTION_TIPS
    //
    //        [self rightBarButton:MYLocalizedString(@"PUBLIC_COMMENT_COMMIT", nil) color:[UIColor blackColor] selector:@selector(commitInfor)];
    //        [self.commentTextView becomeFirstResponder];
    //    } else {
    self.title = MYLocalizedString(@"SITEPLAY_WRITE_COMMENT", nil);
    [self.submitCommentBtn setTitle:MYLocalizedString(@"PUBLIC_COMMENT_COMMIT", nil) forState:UIControlStateNormal];
    [self.feedBackBtn setTitle:MYLocalizedString(@"SETTING_FEEDBACK", nil) forState:UIControlStateNormal];
    
    self.LineQuestionHeadView.hidden = YES;
    self.commentTextView.placeholder =MYLocalizedString(@"SITEPLAY_COMMENT_TIPS", nil);
    
    if (_hasscore) {
        
        [_rateView setScore:_hasscore/10.0];
        _commentTextView.text = self.comment ? self.comment : @" ";
        _CharLimitLabel.hidden = YES;
        _rateView.userInteractionEnabled = NO;
        _commentTextView.userInteractionEnabled = NO;
        
    }else {
        
//        [self rightBarButton:MYLocalizedString(@"PUBLIC_COMMENT_COMMIT", nil) color:[UIColor blackColor] selector:@selector(commitInfor)];
//        [self.commentTextView becomeFirstResponder];
    }
    //    }
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close:)];
    tap.delegate = self;
    
    [self.view addGestureRecognizer:tap];
}

- (void)close:(UITapGestureRecognizer *)tap {
    
    if (self.commentTextView.isFirstResponder) {
        
        [self.commentTextView endEditing:YES];
    }else {
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self appearAnimation];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
    
}
- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
//    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    self.navigationController.navigationBar.hidden = YES;
}
- (void)setHasscore:(NSInteger)hasscore {
    
    _hasscore = hasscore;
    
    [_rateView setScore:_hasscore/10.0];
    _commentTextView.text = self.comment ? self.comment : @" ";
    _CharLimitLabel.hidden = YES;
    _rateView.userInteractionEnabled = NO;
    _commentTextView.userInteractionEnabled = NO;
}

- (IBAction)submitCommentBtnClicked:(UIButton *)sender {
    
    [self commitInfor];
}

- (IBAction)feedBackBtnClicked:(UIButton *)sender {
    
    UIViewController *vc = [IGUtil loadViewController:@"FeedBackVC" storyboard:@"Account"];
    
    [self.navigationController pushViewController:vc animated:YES];
    self.navigationController.navigationBar.hidden = NO;
}


- (void)commitInfor {
    // 提交
    
    NSString *str = self.commentTextView.text;
    
    
    if ([IGUtil isStringLenght0:str]) {
        
        [IGUtil showToast:MYLocalizedString(@"COMMENT_NULL_TIP", nil)];
        return;
    }
    
    [ActivityIndicatorView showHUDAddedTo:self.view];
    @weakify(self);
    [NetAPIManager evaluate:self.relationid isLine:self.isLine score:@(self.score) comment:str Block:^(NSString *result, NSError *error) {
        @strongify(self);
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        if (!error) {
            [self dismissViewControllerAnimated:YES completion:nil];
            if (self.commitBlock) {
                
                self.commitBlock(self.score, str);
            }
            
        }
    }];
    
}


- (void)show:(UIViewController *)vc completeBlock:(void (^) (CGFloat score, NSString *comment))block {
    
    self.commitBlock = block;
    
    self.modalPresentationStyle = UIModalPresentationOverCurrentContext;
//
    UINavigationController * nav = [[UINavigationController alloc] initWithRootViewController:self];

    nav.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [vc presentViewController:nav animated:NO completion:nil];
}

- (void)appearAnimation {
    self.bgViewCenterY.constant = 0;
    
    [UIView animateWithDuration:0.25 animations:^{
        
        [self.view layoutIfNeeded];
    }];
    
//    [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
//        [self.view layoutIfNeeded];
//    } completion:nil];
}


#pragma mark -StarRateViewDelegate

- (void)starRatingView:(StarRateView *)view score:(float)score {
    
    //    NSInteger newScore = ceil(score * 5);
    
    //    NSInteger index = newScore > 0 ? newScore - 1 : 0;
    //    NSString *message = self.messageArray[index];
    
    
    self.score = score * 10;
}


#pragma mark - UITextViewDelegate
#define MAX_STARWORDS_LENGTH 100

- (void)textViewDidChange:(UITextView *)textView {
    
    NSString * string  =  textView.text;
    
    //获取高亮部分
    
    UITextRange * seletedRange = [textView markedTextRange];
    
    UITextPosition * position = [textView positionFromPosition:seletedRange.start offset:0];
    
    // 没有高亮选择的字， 就对其进行字数统计和限制
    
    if (!position) {
        
        if (string.length > MAX_STARWORDS_LENGTH) {
            
            NSRange rangeIndex = [string rangeOfComposedCharacterSequenceAtIndex:MAX_STARWORDS_LENGTH];
            if (rangeIndex.length == 1) {
                
                textView.text = [string substringToIndex:MAX_STARWORDS_LENGTH];
            }else {
                
                NSRange rangeRange = [string rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, MAX_STARWORDS_LENGTH)];
                
                textView.text = [string substringWithRange:rangeRange];
            }
        }
    }
    int length =(int)(MAX_STARWORDS_LENGTH - textView.text.length);
    
    if (length >=0) {
        
        self.CharLimitLabel.text = @(MAX_STARWORDS_LENGTH - textView.text.length).stringValue;
    }
    
}


#pragma mark --

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    if ([touch.view isDescendantOfView:self.bgView]) {
        return NO;
    }
    
    return YES;
}

@end

